import getApiData from '@/services/cpasRequest';
import { msgError } from '@/utils/msg';
import { getFullUserName } from '@/utils/pub';
import { getIsEditOrView } from './component/samplingRecordPopupService';
import { consts } from './consts';
import {
  OverallMode,
  ProjectOverallProps,
  SampleParameterValues,
  SampleRecordEditType,
  SampleReord,
  SampleStepInfo,
} from './typing';
/**
 *获取认定的显示值
 * @param assertionStr
 * @returns
 */
export function getAssertionTexts(assertionStr: string) {
  const values: string[] = (assertionStr || '').split(',');
  return consts.assertions
    .filter((item) => values.includes(item.value))
    .map((item) => item.text)
    .join(',');
}
/**
 *
 * @param dbname 获取抽样记录数据(分页的)
 */
export async function getSampleRecordList(
  dbname: string,
  sampleSource?: string,
  searchValue?: string,
  pageIndex?: number,
  pageSize?: number,
  guidInStr?: string,
): Promise<SampleReord[]> {
  const retData = await getApiData('sample.getSampleRecordList', {
    dbname,
    sortFields: 'createTime',
    pageIndex: pageIndex ?? 0,
    pageSize: pageSize ?? consts.maxSampleCount,
    searchValue,
    sampleSource,
    guidInStr,
  });
  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }
  const rowsData: any[] = retData.data;

  rowsData.forEach((item: any) => {
    item.sampleStepInfoStr = item.sampleStepInfo; //保留起来
    item.sampleStepInfo =
      typeof item.sampleStepInfo === 'string'
        ? JSON.parse(item.sampleStepInfo)
        : item.sampleStepInfo;

    //增加 抽样方法显示值
    const sampleMethodActiveKey =
      typeof item?.sampleStepInfo == 'object' ? item.sampleStepInfo?.sampleMethodActiveKey : '';
    const title = consts.sampleMethodTabsTitle[sampleMethodActiveKey || ''];
    item.sampleMethodText = `${title}-${item.sampleMethod}`;
  });
  return retData.data;
}
/**
 * 获取样本所有记录的表数据
 * @param dbname
 * @param sampleSource
 * @param searchValue
 * @param pageIndex
 * @param pageSize
 * @param guidInStr
 * @returns
 */
export async function getAllSampleRecordTableList(
  dbname: string,
  allSampleRecordTable: string,
  whereSql: string,
  pageIndex?: number,
  pageSize?: number,
): Promise<SampleReord[]> {
  const retData = await getApiData('sample.getAllSampleRecordTableList', {
    dbname,
    fields: '*',
    pageIndex: pageIndex ?? 0,
    pageSize: pageSize ?? consts.maxSampleCount,
    allSampleRecordTable,
    whereSql,
  });
  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }
  const rowsData: any[] = retData.data;
  return rowsData;
}
/**
 * 获取样本所有记录的表数据
 * @param dbname
 * @param allSampleRecordTable
 * @param whereSql
 * @param pageIndex
 * @param pageSize
 * @returns
 */
export async function getallSampleRecordTableRecordGuidArray(
  dbname: string,
  allSampleRecordTable: string,
  whereSql: string,
  pageIndex?: number,
  pageSize?: number,
): Promise<string[]> {
  const rowsData: any[] = await getAllSampleRecordTableList(
    dbname,
    allSampleRecordTable,
    whereSql,
    pageIndex,
    pageSize,
  );
  return rowsData.map((item) => item.record_guid);
}
/**
 * 保存抽样记录
 * @param dbname
 * @param searchValue
 * @param pageIndex
 * @param pageSize
 * @returns
 */
export async function saveSampleRecord(
  dbname: string,
  sampleRecord: SampleReord,
): Promise<boolean> {
  const retData = await getApiData('sample.saveSampleRecord', {
    ...sampleRecord,
    dbname,
    sortFields: 'createTime',
  });
  if (!retData.ok) {
    msgError(retData.data);
  }
  return retData.ok;
}
/**
 * 转换到 SampleStepInfo
 * @param sampleReord
 */
export function convertToSampleStepInfo(sampleReord: SampleReord): SampleStepInfo {
  let sampleStepInfo: SampleStepInfo = {};
  if (typeof sampleReord.sampleStepInfo === 'string') {
    sampleStepInfo = JSON.parse(sampleReord.sampleStepInfo);
  } else if (typeof sampleReord.sampleStepInfo === 'object') {
    sampleStepInfo = sampleReord.sampleStepInfo;
  }
  return sampleStepInfo;
}
/**
 * 转换为 SampleReord
 * @param sampleStepInfo
 * @returns
 */
export function convertToSampleRecord(
  sampleStepInfo: SampleStepInfo,
  curUser: API.CurUser,
): SampleReord {
  const projectOverallProps: ProjectOverallProps = sampleStepInfo.projectOverallProps as any;
  const sampleParameterValues: SampleParameterValues = sampleStepInfo.sampleParameterValues as any;

  //重新来一个
  const newSampleStepInfo: SampleStepInfo = {
    guid: sampleStepInfo.guid,
    sampleParameterValues,
    sampleMethodActiveKey: sampleStepInfo.sampleMethodActiveKey,
    projectOverallProps: {
      ...projectOverallProps,
      sampleTableList: [], //"不需要保存"
      accountInfoList: [], //"不需要保存"
    },
  };
  //计算samplePeriod
  const curDataId = projectOverallProps.curDataId;
  const formQueryParams = projectOverallProps.curWhereSqlParams?.formQueryParams;
  let samplePeriod = `${curDataId}01-${curDataId}12`;
  if (!projectOverallProps.curWhereSqlParams?.isAdvQuery) {
    if (formQueryParams?.monthStartStr && formQueryParams.monthEndStr) {
      samplePeriod = `${formQueryParams.monthStartStr}-${formQueryParams.monthEndStr}`;
    }
  }
  const sampleStepInfoStr = JSON.stringify(newSampleStepInfo);

  const sampleRecord: SampleReord = {
    guid: sampleStepInfo.guid || '',
    samplePeriod: samplePeriod,
    sampleSource:
      projectOverallProps.curSampleTable?.tableName ||
      projectOverallProps.curSampleTable?.tableTitle ||
      '',
    itemName: (projectOverallProps.curSampleItem.itemName || '').substring(0, 200), //取200个长度
    assertion: (projectOverallProps.curSampleItem.assertion || []).join(','),
    sampleMethod: sampleParameterValues?.sampleMethod || '',
    sampleStepInfo: sampleStepInfoStr,
    createUser: getFullUserName(curUser?.usercode, curUser?.username || ''),
    sampleStepInfoStr: '',
  };
  return sampleRecord;
}
/**
 * 删除 抽样记录
 * @param dbname
 * @param sampleRecord
 * @returns
 */
export async function delSampleRecord(
  dbname: string,
  allSampleRecordTable: string,
  guid: string,
): Promise<boolean> {
  const retData = await getApiData('sample.delSampleRecord', {
    guid,
    dbname,
    allSampleRecordTable,
  });
  if (!retData.ok) {
    msgError(retData.data);
  }
  return retData.ok;
}

export function downloadContent(content: string, filename: string) {
  // 创建一个 Blob 对象，包含要下载的内容
  const blob = new Blob([content], { type: 'text/plain' });

  // 创建一个指向 Blob 的 URL
  const url = URL.createObjectURL(blob);

  // 创建一个隐藏的 <a> 元素
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.title = filename;
  a.download = filename;

  // 将 <a> 元素添加到 DOM 中
  document.body.appendChild(a);

  // 触发点击事件
  a.click();

  // 清理资源
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

/**
 * 获取样本源表数据最大长度
 * @param dbname
 * @param tableName
 * @param fieldName
 */
export async function getExistsDataId(dbname: string, defaultDataId: string) {
  const retData = await getApiData('sample.getExistsDataId', { dbname });

  if (!retData.ok) {
    msgError(retData.data);
    return defaultDataId;
  }
  return retData.data?.dataId || defaultDataId;
}
/**
 * 增加或编辑样本记录
 * @param sampleRecordEditType
 * @param dbname
 * @param samplingRecordPopupRef
 * @param curUser
 * @param dataGridData
 * @param sampleRecord
 * @param refreshData
 * @param setIsNeedSamplingRecordPopup
 */

export async function addOrEditOrViewSampleRecord(
  sampleRecordEditType: SampleRecordEditType,
  dbname: string,
  samplingRecordPopupRef: any, // useRef<any>(null)
  curUser: API.CurUser,
  dataGridData: SampleReord[],
  sjnd: string,
  sampleRecord?: SampleReord,
  refreshData?: () => void,
  setIsNeedSamplingRecordPopup?: (value: boolean) => void,
) {
  const sampleStepInfoOfParams = sampleRecord ? convertToSampleStepInfo(sampleRecord) : undefined;
  console.log('sampleStepInfoOfParams:', sampleStepInfoOfParams);
  //如果是编辑模式
  if (getIsEditOrView(sampleRecordEditType) && sampleStepInfoOfParams?.projectOverallProps) {
    sampleStepInfoOfParams.projectOverallProps.overallMode = OverallMode.overallEdit;
  }
  const existsDataId = await getExistsDataId(dbname, sjnd);
  setIsNeedSamplingRecordPopup && setIsNeedSamplingRecordPopup(true);
  //用一个定时器来显示pupop
  const interval = setInterval(() => {
    if (samplingRecordPopupRef.current) {
      clearInterval(interval);
      samplingRecordPopupRef.current.show({
        existsDataId, //有数据的dataId
        sampleRecordEditType /* : sampleRecord ? SampleRecordEditType.edit : SampleRecordEditType.add */,
        sampleStepInfo: sampleStepInfoOfParams,
        // sampleRecord: sampleRecord,
        //保存
        saveSampleRecord: async (sampleStepInfo: SampleStepInfo) => {
          const sampleRecord: SampleReord = convertToSampleRecord(sampleStepInfo, curUser);
          await saveSampleRecord(dbname, sampleRecord);
        },
        //关闭
        closeSamplingRecordPopup: (isFinished: boolean) => {
          if (!isFinished) {
            //取消了
            if (sampleStepInfoOfParams) {
              const sampleReord2 = dataGridData.find(
                (item) => item.guid == sampleStepInfoOfParams.guid,
              );

              if (sampleReord2 && sampleReord2.sampleStepInfoStr) {
                sampleReord2.sampleStepInfo = JSON.parse(sampleReord2.sampleStepInfoStr);
              }
            }
          }
          setIsNeedSamplingRecordPopup && setIsNeedSamplingRecordPopup(false);
        },
        //保存并刷新
        saveSampleRecordAndRefresh: async (sampleStepInfo: SampleStepInfo) => {
          const sampleRecord: SampleReord = convertToSampleRecord(sampleStepInfo, curUser);

          await saveSampleRecord(dbname, sampleRecord);
          refreshData && refreshData();
        },
      });
    }
  }, 10);
}

// 调用函数，保存内容
